#!/usr/bin/python3
# -*- coding: utf8 -*-
# Date   : 2021/07/29
# Author : Kwan
# Email  : allenxian@live.com
# Blog   : https://my.oschina.net/u/4173440

from datetime import datetime, timedelta
from project.flasky import db
from project.define import db_logger


DataName = "月租用户"
TableName = "app_members_user"


class MemberUser(db.Model):
    """
    月租用户
    """
    __tablename__ = TableName
    # 用户ID
    UserID = db.Column(db.Integer, primary_key=True, autoincrement=True, nullable=False)
    # 车型
    VehicleType = db.Column(db.String(16), nullable=False)
    # 用户类型：Monthly 普通月租 Private 专用月租
    ParkingType = db.Column(db.String(16), nullable=False)
    # 车牌，可以绑定多个，以,隔开
    LicensePlate = db.Column(db.String(64), nullable=False, unique=True)
    # 卡号
    CardNumber = db.Column(db.String(16))
    # 用户名
    UserName = db.Column(db.String(64))
    # 联系电话
    Phone = db.Column(db.String(16))
    # 创建时间
    CreateTime = db.Column(db.DateTime)
    # 有效期
    ValidTime = db.Column(db.DateTime)
    # 启用
    Enable = db.Column(db.Boolean, default=True)

    def __init__(self, **kwargs) -> None:
        super().__init__()
        self.VehicleType = kwargs.get('VehicleType')
        self.ParkingType = kwargs.get('ParkingType')
        self.LicensePlate = self.__check_license_plate(kwargs.get('LicensePlate'))
        self.CardNumber = kwargs.get('CardNumber')
        self.UserName = kwargs.get('UserName')
        self.Phone = kwargs.get('Phone')
        self.CreateTime = datetime.now()
        self.ValidTime = datetime.strptime(kwargs.get('ValidTime'), '%Y/%m/%d')

    def datetime_string(self, val):
        """
        datetime转换
        """
        if isinstance(val, datetime):
            return val.strftime('%Y/%m/%d')

    def __check_license_plate(self, lp):
        """
        检查车牌有效性
        """
        if len(lp) == 6:
            return lp.upper()
        else:
            if "，" in lp:
                lp.replace("，",",")
            return lp.upper()

    def to_dict(self):
        """
        转换键值对
        """
        def convert_data(data):
            """
            转换数据类型
            """
            if isinstance(data, datetime):
                return data.strftime('%Y/%m/%d')
            else:
                return data

        return dict([(c.name, convert_data(getattr(self, c.name))) for c in self.__table__.columns])

    def parking_valid_renewal(self, **kwargs):
        """
        更新有效期
        """
        renewal = kwargs.get('Renewal')
        if renewal:
            self.ValidTime = datetime.strptime(renewal, '%Y/%m/%d')
        db.session.commit()
        return self.to_dict()

    @staticmethod
    def selected_data(**kwargs):
        """
        选中数据
        """
        user_id = kwargs.get('UserID')
        if user_id:
            return MemberUser.query.filter_by(UserID=user_id).first()

    @staticmethod
    def columns_name():
        """
        数据表标题
        """
        ColumnName = {
            'UserID':'用戶ID','VehicleType':'車輛類型','ParkingType':'車位類型','LicensePlate':'車牌綁定','CardNumber': '月租卡號', 
            'UserName': '用戶名','Phone':'聯係電話','CreateTime':'創建時間','ValidTime':'有效期','Enable':'使用狀態'
            }
        return ColumnName

    @staticmethod
    def generate_filters(**kwargs):
        """
        筛选器
        """
        filters = set()
        for k, v in kwargs.items():
            if v:
                if hasattr(MemberUser, k):
                    if k == 'VehicleType':
                        filters.add(MemberUser.VehicleType == v)
                    elif k == 'ParkingType':
                        filters.add(MemberUser.ParkingType == v)
                    elif k == 'LicensePlate':
                        filters.add(MemberUser.LicensePlate.like(f"%{v}%"))
                    elif k == 'CardNumber':
                        filters.add(MemberUser.CardNumber.like(f"%{v}%"))
                    elif k == 'UserName':
                        filters.add(MemberUser.UserName.like(f"%{v}%"))
                    elif k == 'Phone':
                        filters.add(MemberUser.Phone.like(f"%{v}%"))
                    elif k == 'CreateTime':
                        if " - " in v:
                            start, end = [datetime.strptime(i, "%Y/%m/%d %H:%M:%S") for i in v.split(' - ') ]
                            filters.add(MemberUser.CreateTime.between(start, end))
                    elif k == 'ValidTime':
                        if " - " in v:
                            start, end = [datetime.strptime(i, "%Y/%m/%d %H:%M:%S") for i in v.split(' - ') ]
                            filters.add(MemberUser.ValidTime.between(start, end))
                    elif k == 'Enable':
                        filters.add(MemberUser.Enable == v)
        return filters
    
    @staticmethod
    def check_exists(**kwargs):
        """
        规则是否存在
        """
        lp = kwargs.get('LicensePlate')
        if lp:
            return MemberUser.query.filter(MemberUser.LicensePlate.like(f"%{lp}%")).first()

    @staticmethod
    def insert_data(**kwargs):
        """
        新增
        """
        try:
            r = MemberUser(**kwargs)
            db.session.add(r)
            db.session.commit()
            db_logger.debug(f"{TableName} => 新增{DataName}成功：{kwargs}")
            return r.to_dict()
        except Exception as e:
            db.session.rollback()
            db_logger.error(f"{TableName} => 新增{DataName}失败：{kwargs} 原因：{e}")

    @staticmethod
    def delete_data(**kwargs):
        """
        删除
        """
        try:
            r = MemberUser.selected_data(**kwargs)
            if r:
                db.session.delete(r)
                db.session.commit()
                db_logger.debug(f"{TableName} => 删除{DataName}成功：{kwargs}")
                return r.to_dict()
        except Exception as e:
            db.session.rollback()
            db_logger.error(f"{TableName} => 删除{DataName}失败：{kwargs} 原因：{e}")

    @staticmethod
    def modify_data(**kwargs):
        """
        修改车位
        """
        try:
            r = MemberUser.selected_data(**kwargs)
            if r:
                for k, v in kwargs.items():
                    if hasattr(r, k):
                        if k == "ValidTime":
                            v = datetime.strptime(v, '%Y/%m/%d')
                        if getattr(r, k) != v:
                            setattr(r, k, v)
                            update = True
                if update:
                    try:
                        db.session.commit()
                        db_logger.debug(f"{TableName} => 更新{DataName}成功：{kwargs}")
                        return r.to_dict()
                    except Exception as e:
                        db.session.rollback()
                        db_logger.error(f"{TableName} => 更新{DataName}失败：{kwargs} 原因：{e}")
                        update = False
                else:
                    return "ignore"
            return update
        except Exception as e:
            db_logger.error(f"{TableName} => 更新{DataName}参数错误：{kwargs} 原因：{e}")
    
    @staticmethod
    def table_init():
        """
        初始化数据
        """
        demo_data = [
            {'VehicleType':'Car','ParkingType':'Monthly','LicensePlate':'MC0005','CardNumber': '1111122222', 
            'UserName': '月租用戶1','Phone':'12345678','ValidTime':'2099/1/1'},
            {'VehicleType':'Moto','ParkingType':'Monthly','LicensePlate':'MM0005','CardNumber': '3333344444', 
            'UserName': '月租用戶2','Phone':'12345678','ValidTime':'2099/1/1'},
            {'VehicleType':'Car','ParkingType':'Monthly','LicensePlate':'MC0006','CardNumber': '5555566666', 
            'UserName': '月租用戶3','Phone':'12345678','ValidTime':'2099/1/1'},
            {'VehicleType':'Moto','ParkingType':'Monthly','LicensePlate':'MM0006','CardNumber': '7777788888', 
            'UserName': '月租用戶4','Phone':'12345678','ValidTime':'2099/1/1'},
            {'VehicleType':'Car','ParkingType':'Private','LicensePlate':'MC0007','CardNumber': '2222211111', 
            'UserName': '專用用戶5','Phone':'12345678','ValidTime':'2099/1/1'},
            {'VehicleType':'Moto','ParkingType':'Private','LicensePlate':'MM0007','CardNumber': '4444433333', 
            'UserName': '專用用戶6','Phone':'12345678','ValidTime':'2099/1/1'},
            {'VehicleType':'Car','ParkingType':'Private','LicensePlate':'MC0008','CardNumber': '6666655555', 
            'UserName': '專用用戶7','Phone':'12345678','ValidTime':'2099/1/1'},
            {'VehicleType':'Moto','ParkingType':'Private','LicensePlate':'MM0008','CardNumber': '8888877777', 
            'UserName': '專用用戶8','Phone':'12345678','ValidTime':'2099/1/1'},
        ]
        for i in demo_data:
            if not MemberUser.check_exists(**i):
                MemberUser.insert_data(**i)

